import 'dart:convert';

import 'package:app/model/user/login_user_info.dart';
import 'package:app/utils/preferences_utils.dart';

class UserStates {
  static final UserStates _instance = UserStates._internal();

  static bool _isLogin = false;

  static LoginUserInfo? _loginUserInfo;

  static UserStates get instance => UserStates();

  get isLogin {
    return _isLogin;
  }

  UserStates._internal() {
    PreferenceUtils.instance.getString("login:user:info", "").then((value) {
      if (value == '') {
        _isLogin = false;
        _loginUserInfo = null;
        return;
      }
      _isLogin = true;
      _loginUserInfo = LoginUserInfo.fromJsonString(value);
    });
  }

  factory UserStates() => _instance;

  void login(Map<String, dynamic> userInfoMap) {
    _loginUserInfo = LoginUserInfo.fromMap(userInfoMap);
    _isLogin = true;
    PreferenceUtils.instance
        .saveString("login:user:info", json.encode(userInfoMap));
  }

  void logout() {
    clear();
  }

  void loadData() {}

  void clear() {
    _isLogin = false;
    _loginUserInfo = null;
    PreferenceUtils.instance.saveString("login:user:info", '');
  }

  LoginUserInfo? getLoginUserInfo() {
    return _loginUserInfo;
  }
}
